﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ChBusiness.Wsbs;
using ChBusiness.User;
using ChBusiness;
using ChBusiness.FlowOperation;
using ChBusiness.Menu;
using ChBusiness.Common;

public partial class MainPage : System.Web.UI.Page
{
    private WebWork cWorks = new WebWork();
    private DataTable dtSerialNames = new DataTable();
    private DataTable dtMenu = new DataTable();
    private SerialInstance cInstance = new SerialInstance();
    private ShenBaoSubmit cSubmit = new ShenBaoSubmit();
    private Messagebox cMessage = new Messagebox();
    private ClsMenuOperation menuOperation = new ClsMenuOperation();
    private SerialInstanceOperation instanceOperation = new SerialInstanceOperation();

    private string strNoSubmit = string.Empty; //新申(尚未提交)请事项个数
    private string strInstance = string.Empty; //正在办理(当前办理)事项个数
    private string strBuZheng = string.Empty; //补正补齐办理事项个数
    private string strHistory = string.Empty; //历史办理事项个数
    private string strBoHui = string.Empty; //驳回办理事项个数
    private string strShouJian = string.Empty; //累计收件个数
    private string strBanJie = string.Empty; //累计办结个数
    private string strTongZhi = string.Empty; //通知个数
    private string strconflag = string.Empty;//弹出模式对话框类型
    private string strUserId = string.Empty;//用户ID
    private string strInadmissible = string.Empty;//不予受理
    private string strNotpassed = string.Empty;//未通过办理

    #region 页面加载
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["UserId"] == null)
        {
            if (Session["MainPage"] != null)
            {            

                Response.Redirect(Session["MainPage"].ToString());
            }
            else
            {
                Response.Redirect(SystemConfig.LoginPage);
            }
        }

        if (!IsPostBack)
        {
            BindFlowName();
            dtMenu = menuOperation.GetChildMenus("网上办事");

            //绑定行政许可事项
            DataTable dtTable = cWorks.GetWorkFlow();
            RepeaterWeb.DataSource = dtTable;
            RepeaterWeb.DataBind();
            BindXzxkjgData();

            BindQuestion();//绑定常见问题
            BindLyzx();//绑定留言咨询
            msgXxgg.MsgDataType = "信息公告";//绑定信息公告

            strUserId = string.Empty;
            if (Session["UserId"] != null)
            {
                strUserId = Session["UserId"].ToString();

                strNoSubmit = cSubmit.GetNoSubmitCount(strUserId);//新申(尚未提交)请事项个数
                strInstance = cInstance.GetInstanceCount(strUserId);//正在办理(当前办理)事项个数
                strBuZheng = cSubmit.GetBuZhengSubmitCount(strUserId);//补正补齐办理事项个数
                strHistory = cInstance.GetHistoryCount(strUserId,"1");//已通过办理事项个数
                strBoHui = cInstance.GetBoHuiCount(strUserId);//驳回办理事项个数
                strShouJian = cInstance.GetShoujianCount(strUserId);//累计收件个数
                strBanJie = cInstance.GetBanjieCount(strUserId); //累计办结个数
                strTongZhi = cMessage.GetMessageCount(strUserId);//通知个数
                strInadmissible = cInstance.GetHistoryCount(strUserId, "-3"); //不予受理
                strNotpassed = cInstance.GetHistoryCount(strUserId, "-4");//未通过办理
            }
            
        }        
    }
    #endregion

    #region 信息绑定
    /// <summary>
    /// 绑定常见问题
    /// </summary>
    /// <!--addby zhongjian 20091028-->
    public void BindQuestion()
    {
        DataTable dtSource = instanceOperation.GetAskQuestion("", "常见问题", "", 4,13);
        rptAskQuestion.DataSource = dtSource;
        rptAskQuestion.DataBind();
    }

    /// <summary>
    /// 绑定留言咨询
    /// </summary>
    /// <!--addby zhongjian 20091028-->
    public void BindLyzx()
    {
        DataTable dtSource = instanceOperation.GetLyzxInfo("", true, 4, 13,"","","","","");
        rptLYZX.DataSource = dtSource;
        rptLYZX.DataBind();
    }
    
    /// <summary>
    /// 个人信息公示
    /// </summary>
    /// <returns></returns>
    protected string GetGeRen()
    {
        if (Session["UserId"] != null)
        {
            strUserId = Session["UserId"].ToString();
            //为单位用户管理员时,展示管理员添加用户的功能 addby zhongjian 20100125
            DataTable dtTemp= menuOperation.SelectUnitsAdmin(strUserId);
            if (dtTemp.Rows.Count>0)
            {
                dtMenu = menuOperation.GetChildMenus("个人信息管理");
            }
            else
            {
                //非单位管理用户个人信息菜单
                dtMenu = menuOperation.GetChildMenusPersonal();
            }
        }
        string strHtml = string.Empty;

        foreach (DataRow drTemp in dtMenu.Rows)
        {
            string strMenuTitle = drTemp["menu_title"].ToString();
            string strMenuUrl = drTemp["menu_url"].ToString();
            strHtml += string.Format("<tr><td style=\"width:35px;\" align=\"right\"><img src=\"App_Themes/SkinFile/Images/ico-01.gif\" alt=\"\" />&nbsp;&nbsp;</td><td align=\"left\"><a href='{0}' target=\"_blank\"><font color=\"black\">{1}</font></a></td></tr>",
                        strMenuUrl.Replace("~/", ""), strMenuTitle);
        }
        
        return strHtml;
    }
    #endregion

    #region 行政许可结果公示
    /// <summary>
    /// Binds the data.
    /// </summary>
    private void BindXzxkjgData()
    {
        DataTable dtSource = instanceOperation.GetInstanceInfo("", "", "", "", "");

        this.dgXkjggs.DataSource = dtSource;
        this.dgXkjggs.PageSize = SystemConfig.PageSize;
        this.dgXkjggs.RecordCount = dtSource.Rows.Count;
        this.dgXkjggs.DataBind();
    }

    /// <summary>
    /// Handles the OnLoadData event of the dgXkjggs control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void dgXkjggs_OnLoadData(object sender, EventArgs e)
    {
        BindXzxkjgData();
    }
    #endregion

    #region 行政许可事项查看
    /// <summary>
    /// 获取行政许可事项查看
    /// </summary>
    /// <param name="row">The row.</param>
    /// <returns></returns>
    protected string GetKaifang(string strFlowName, string strFlowType, string strInterfaceType, string strInterfaceUrl)
    {
        string strHtml = string.Empty;
        string strWorkFlow = strFlowName;
        strFlowName = Server.UrlEncode(strFlowName);
        strFlowType = Server.UrlEncode(strFlowType);
        foreach (DataRow drTemp in dtMenu.Rows)
        {
            string strMenuTitle = drTemp["menu_title"].ToString();
            string strMenuUrl = drTemp["menu_url"].ToString();
            //string strInterfaceType = Eval("INTERFACETYPE") == null ? "" : Eval("INTERFACETYPE").ToString();
            //string strInterfaceUrl = Eval("INTERFACEURL") == null ? "" : Eval("INTERFACEURL").ToString(); 

            ////当接口启用状态开启时，在点击“在线申报”后，应连接接口页面。 addby zhongjian 20091210
            if (strMenuTitle == "在线申报" && strInterfaceType == "1")
            {
                strMenuUrl = GetDXInterfaceUrl(strInterfaceUrl);
                strHtml += string.Format("<td ><a href='{0}&flowname={1}&flowtype={3}' target=\"_blank\"><font color=\"black\">{2}</a></font></td>",
                   strMenuUrl.Replace("~/", ""), strFlowName, strMenuTitle, strFlowType);
            }
            else
            {
                //添加模式对话框显示类型&DialogFlag=Show,只有从本地址连接过去的在线申报,才提示申报的方式. addby zhongjian 20100315
                strHtml += string.Format("<td ><a href='{0}&flowname={1}&flowtype={3}&DialogFlag=Show' target=\"_blank\"><font color=\"black\">{2}</a></font></td>",
                   strMenuUrl.Replace("~/", ""), strFlowName, strMenuTitle, strFlowType);
            }
        }

        return strHtml;
    }
  
    /// <summary>
    /// 关闭事项,不可查看
    /// </summary>
    /// <returns></returns>
    protected string GetGuanbi()
    {
        string strHtml = string.Empty;

        foreach (DataRow drTemp in dtMenu.Rows)
        {
            string strMenuTitle = drTemp["menu_title"].ToString();

            strHtml += string.Format("<td ><font color=\"gray\">{0}</font></td>", strMenuTitle);
        }

        return strHtml;
    }

    /// <summary>
    /// 获取有匿名权限查看的菜单
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    /// <!--addby zhongjian 20091102-->
    protected string GetMenuTypePower(string strFlowName, string strFlowType)
    {
        string strHtml = string.Empty;

        //获取菜单
        ClsMenuOperation menuOperation = new ClsMenuOperation();
        DataTable dtMenu = menuOperation.GetChildMenus("网上办事");

        //获取菜单权限
        DataTable dtMenuRight = cWorks.GetChildMenuRight(strFlowName);
        strFlowName = Server.UrlEncode(strFlowName);
        strFlowType = Server.UrlEncode(strFlowType);
        foreach (DataRow drTemp in dtMenu.Rows)
        {
            string strMenuTitle = drTemp["menu_title"].ToString();
            string strMenuUrl = drTemp["menu_url"].ToString();

            dtMenuRight.DefaultView.RowFilter = string.Format("menu_name='{0}'", strMenuTitle);

            if (dtMenuRight.DefaultView.Count > 0)
            {
                if (dtMenuRight.DefaultView[0].Row["menu_type"].ToString() == "1")
                {
                    strHtml += string.Format("<td ><a href='{0}&flowname={1}&flowtype={3}' target=\"_blank\"><font color=\"black\">{2}</a></font></td>",
                        strMenuUrl.Replace("~/", ""), strFlowName, strMenuTitle, strFlowType);
                }
                else
                {
                    strHtml += string.Format("<td ><font color=\"gray\">{0}</font></td>", strMenuTitle);
                }
            }
        }

        return strHtml;
    } 

    /// <summary>
    ///构建数据行结构
    /// </summary>
    /// <param name="row">数据行</param>
    /// <returns></returns>
    protected string GetContent(IDataItemContainer row)
    {
        string strUserId = Session["UserID"].ToString();        
        dtSerialNames = UserHandle.GetSerialName(strUserId);

        string strFlowName = (string)DataBinder.Eval(row.DataItem, "FLOWNAME");
        string strFlowType = (string)DataBinder.Eval(row.DataItem, "FLOWTYPE");//流程别名

        object objTemp = DataBinder.Eval(row.DataItem, "INTERFACETYPE");//获取接口类型
        string strInterfaceType = objTemp == DBNull.Value ? "" : objTemp.ToString();

        objTemp = DataBinder.Eval(row.DataItem, "INTERFACEURL");//获取接口地址
        string strInterfaceUrl = objTemp == DBNull.Value ? "" : objTemp.ToString();

        bool bSeial = false;
        for (int i = 0; i < dtSerialNames.Rows.Count; i++)
        {
            if (dtSerialNames.Rows[i]["SERIAL_NAME"].ToString() == strFlowName)
            {
                bSeial = true;
                break;
            }
        }

        string strType = UserHandle.GetUserType(strUserId);
        if (strType == SystemConfig.CszcUserType)//初始注册用户
        {
            //return GetGuanbi();
            return GetMenuTypePower(strFlowName,strFlowType);
        }
        else
        {
            if (bSeial)
                return GetKaifang(strFlowName, strFlowType, strInterfaceType, strInterfaceUrl);
            else
                //return GetGuanbi();
                return GetMenuTypePower(strFlowName, strFlowType);
        }
    }

    #endregion

    #region 导航申报
    /// <summary>
    /// Gets the navigation.
    /// </summary>
    /// <returns></returns>
    protected string GetNavigation()
    {
        dtMenu = menuOperation.GetChildMenus("导航申报");
        string strHtml = string.Empty;
        string strCount = string.Empty;

        foreach (DataRow drTemp in dtMenu.Rows)
        {
            string strMenuTitle = drTemp["menu_title"].ToString().Trim ();
            string strMenuUrl = drTemp["menu_url"].ToString();
            int num=strMenuUrl.IndexOf("=");
            string strType = string.Empty;
            if (num > 0)
            {
                try
                {
                    strType = strMenuUrl.Substring(num + 1, 1);
                }
                catch
                { }
            }
            switch(strType)
            {
                case "0":
                    strCount = strNoSubmit;//尚未提交事项
                    break;
                case "1":
                    strCount = strInstance;//当前办理事项
                    break;
                case "2":
                    strCount = strBuZheng;//补正补齐办理事项
                    break;
                case "3":
                    strCount = strHistory;//通过办理事项
                    break;
                case "4":
                    strCount = strBoHui;//驳回办理事项
                    break;
                case "5":
                    strCount = strInadmissible;//不予受理事项
                    break;
                case "6":
                    strCount = strNotpassed;//未通过办理事项
                    break;
                default:
                    strCount = string.Empty;
                    break;
            }

            //添加事项办理权限申请的特殊处理 addby zhongjian 20091201
            if (strMenuTitle == "事项办理权限申请")
            {
                strMenuTitle = string.Format("<font color='red'>{0}</font>", strMenuTitle);
            }
            else
                strCount += "件";

            strHtml += string.Format("<tr><td style=\"width:35px;\" align=\"right\"><img src=\"App_Themes/SkinFile/Images/ico-01.gif\" alt=\"\" />&nbsp;&nbsp;</td><td align=\"left\"><a href='{0}' target=\"_blank\"><font color=\"black\">{1}</font></a> {2}</td></tr>",
                strMenuUrl.Replace("~/", ""), strMenuTitle, strCount);
        }
        return strHtml;
    }
    #endregion

    #region 办件统计
    protected string GetInstanceCount()
    {
        return strInstance;
    }
    
    //新申请事项个数
    protected string GetSubmitCount()
    {
        return strNoSubmit;
    }
    
    //累计收件个数
    protected string GetShoujianCount()
    {
        return strShouJian;
    }
    
    //累计办结个数
    protected string GetBanjieCount()
    {
        return strBanJie;
    }

    //通知个数
    protected string GetMessageCount()
    {
        return strTongZhi;
    }
    #endregion

    #region 绑定流程名称（办理事项）
    /// <summary>
    /// 绑定流程名称
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    /// <!--addby zhongjian 20091109-->
    protected string GetTitleName(IDataItemContainer row)
    {
        string strHtml = string.Empty;
        bool flag=false;
        string strUserID=string.Empty;
        if (Session["UserID"] != null)
        {
            strUserID = Session["UserID"].ToString();
        }
        string strFlowName = (string)DataBinder.Eval(row.DataItem, "FLOWNAME");
        string strFlowType = (string)DataBinder.Eval(row.DataItem, "FLOWTYPE");
        string FlowName = Server.UrlEncode(strFlowName);
        string FlowType = Server.UrlEncode(strFlowType);
        //添加单个办理事项的连接 addby zhongjian 20100111
        flag = UserHandle.GetPower(strUserID, strFlowName);
        if (flag)
            strFlowType += "（可办理）";
        strHtml += string.Format(@"<td colspan='8'>
                                    <div class='page_bar_02' style='text-align: left'><a href='Wsbs/IndexPage.aspx?&flowname={1}&flowtype={2}&type=0' target='_blank'>{0}</a></div>
                                   </td>", strFlowType,FlowName,FlowType);

        return strHtml;
    }
    #endregion

    #region 地理信息平台入口
    /// <summary>
    /// 地理信息中心接口
    /// </summary>
    /// <param name="strUrl">接口连接地址(url)</param>
    /// <returns></returns>
    /// <!--addby zhongjian 20091210-->
    public string GetDXInterfaceUrl(string strInterfaceUrl)
    {
        string strUrl = string.Empty;
        string UserID = string.Empty;
        string strUserPWD = string.Empty;
        if (Session["UserID"] != null)
            UserID = Session["UserID"].ToString();
        strUserPWD = cInstance.GetUserPWD(UserID);
        UserID = HttpUtility.UrlEncode(UserID);//在地信中心传入USERID需加密 addby zhongjian 20100226
        //strInterfaceUrl=System.Configuration.ConfigurationManager.AppSettings["DXInterfaceUrl"];
        strUrl = string.Format("{2}?userId={0}&userPwd={1}", UserID, strUserPWD, strInterfaceUrl);
        return strUrl;
    }
    #endregion

    /// <summary>
    /// 获取当前提示下应该操作的路径
    /// </summary>
    /// <returns></returns>
    /// <!--addby zhongjian 20091203-->
    public string GetMsgUrl()
    {
        string strUrl = "Wsbs/submit.aspx?flag=1";
        string strStepName = string.Empty;
        DataTable dtTemp;
        if (Session["UserId"] != null)
        {
            strUserId = Session["UserId"].ToString();
            strStepName = cInstance.GetStepName(strUserId);
            if (strStepName == "用户注册")
                strUrl = "Wsbs/SelectSerialOperation.aspx";
            //当为权限开能时,导航提示连接为在线申报.
            //在线申报连接的地址当以是否启用接口地址的设置为准. update by zhongjian 20091216
            else if (strStepName == "权限开通")
            {
                dtTemp = cInstance.GetNewWork(strUserId);
                if (dtTemp.Rows.Count > 0)
                {
                    string strFaceType = dtTemp.Rows[0]["interfacetype"].ToString();
                    string strFaceUrl = dtTemp.Rows[0]["interfaceurl"].ToString();
                    if (strFaceType == "1")
                    {
                        strUrl = GetDXInterfaceUrl(strFaceUrl);
                    }
                    else
                    {
                        string strName = dtTemp.Rows[0]["flowname"].ToString();
                        string strType = dtTemp.Rows[0]["flowtype"].ToString();
                        strName = Server.UrlEncode(strName);
                        strType = Server.UrlEncode(strType);
                        //获取userid对应的sessionid
                        ChBusiness.FlowOperation.SerialInstanceOperation sioTemp = new ChBusiness.FlowOperation.SerialInstanceOperation();
                        decimal decValue = Convert.ToDecimal(sioTemp.GetValue("ss_instance_id"));
                        strUrl = string.Format("Wsbs/ShenBao.aspx?flowname={0}&iid={1}&flowtype={2}", strName, decValue, strType);

                    }
                }
                else
                {
                    strUrl = "Wsbs/SelectSerialOperation.aspx";
                }
            }
            else if (strStepName == "尚未提交")
            {                
                strUrl = "Wsbs/submit.aspx?flag=0";
            }
            else if (strStepName == "已经提交")
                strUrl = "Wsbs/submit.aspx?flag=1";
            else if (strStepName == "业务受理")
            {
                strUrl = "Wsbs/submit.aspx?flag=1";
                string strIID=cMessage.GetMessageIID(strUserId);
                if (!string.IsNullOrEmpty(strIID))
                {
                    DataTable dtInfo = cMessage.GetSubmitInfo(strUserId, strIID);
                    if (dtInfo.Rows.Count > 0)
                    {
                        string strSubmitFlag = dtInfo.Rows[0]["submitflag"].ToString();
                        string strFlowType = dtInfo.Rows[0]["flowtype"].ToString();
                        string strUserName = Session["LoginUserName"].ToString();
                        if (strSubmitFlag == "2")//补发通过办理消息
                        {
                            strUrl = "Wsbs/submit.aspx?flag=3";
                            dtTemp = cMessage.GetRequestSet(0, "通过办理");
                            string strMsgContent = string.Empty;
                            string strStepNo = string.Empty;
                            if (dtTemp.Rows.Count > 0)
                            {
                                strStepNo = dtTemp.Rows[0]["step_no"].ToString();
                                strMsgContent = dtTemp.Rows[0]["step_msg"].ToString();
                                if (!string.IsNullOrEmpty(strMsgContent))//当消息内容设置为空时，将不再发送消息。update by zhongjian 20091230
                                {
                                    try
                                    {
                                        strMsgContent = string.Format(strMsgContent, strUserName, strFlowType);
                                    }
                                    catch { }
                                    //添加消息
                                    cMessage.InsertMeaasge(strMsgContent, "", strUserName, strUserId);
                                }
                                cMessage.UpdateUserStepNO(strUserId, strStepNo);
                            }
                        }
                    }
                }
            }
            else if (strStepName == "补正补齐")
                strUrl = "Wsbs/submit.aspx?flag=2";
            else if (strStepName == "通过办理")
                strUrl = "Wsbs/submit.aspx?flag=3";
            else if (strStepName == "驳回办理")
                strUrl = "Wsbs/submit.aspx?flag=4";
            else if (strStepName == "不予受理")
                strUrl = "Wsbs/submit.aspx?flag=5";
            else if (strStepName == "未通过办理")
                strUrl = "Wsbs/submit.aspx?flag=6";

        }
        return strUrl;
    }

    /// <summary>
    /// 绑定所有流程名称
    /// </summary>
    public void BindFlowName()
    {
        UserRightRequest urrTemp = new UserRightRequest();
        DataTable dtTable = urrTemp.GetFlowList();
        ddlFlow.Items.Clear();
        ddlFlow.Items.Add(new ListItem("请选择事项流程...", "0"));
        foreach (DataRow row in dtTable.Rows)
        {
            ddlFlow.Items.Add(new ListItem(row["KEYVALUE"].ToString(), row["KEYVALUE"].ToString()));
        }
    }
}
